<script>
function ok(a, msg) {
  parent.postMessage({ type: "check", status: !!a, message: msg }, "*");
}

function is(a, b, msg) {
  ok(a === b, msg);
}

function testWebIDL() {
  ok("FetchController" in self, "We have a FetchController prototype");
  ok("FetchSignal" in self, "We have a FetchSignal prototype");

  var fc = new FetchController();
  ok(!!fc, "FetchController can be created");
  ok(fc instanceof FetchController, "FetchController is a FetchController");

  ok(!!fc.signal, "FetchController has a signal");
  ok(fc.signal instanceof FetchSignal, "fetchSignal is a FetchSignal");
  is(fc.signal.aborted, false, "By default FetchSignal.aborted is false");
  next();
}

function testUpdateData() {
  var fc = new FetchController();
 
  is(fc.signal.aborted, false, "By default FetchSignal.aborted is false");
 
  fc.abort();
  is(fc.signal.aborted, true, "Signal is aborted");
 
  next();
}
 
function testAbortEvent() {
  var fc = new FetchController();
  fc.signal.onabort = function(e) {
    is(e.type, "abort", "Abort received");
    next();
  }
  fc.abort();
}
 
function testAbortedFetch() {
  var fc = new FetchController();
  fc.abort();

  fetch('slow.sjs', { signal: fc.signal }).then(() => {
    ok(false, "Fetch should not return a resolved promise");
  }, e => {
    is(e.name, "AbortError", "We have an abort error");
  }).then(next);
}

function testFetchAndAbort() {
  var fc = new FetchController();

  var p = fetch('slow.sjs', { signal: fc.signal });
  fc.abort();

  p.then(() => {
    ok(false, "Fetch should not return a resolved promise");
  }, e => {
    is(e.name, "AbortError", "We have an abort error");
  }).then(next);
}

function testWorkerAbortedFetch() {
  var w = new Worker('worker_fetch_controller.js');
  w.onmessage = function(e) {
    ok(e.data, "Abort + Fetch works in workers");
    next();
  }
  w.postMessage('testWorkerAbortedFetch');
}

function testWorkerFetchAndAbort() {
  var w = new Worker('worker_fetch_controller.js');
  w.onmessage = function(e) {
    ok(e.data, "Abort + Fetch works in workers");
    next();
  }
  w.postMessage('testWorkerFetchAndAbort');
}

var steps = [
  // Simple stuff
  testWebIDL,
  testUpdateData,

  // Event propagation
  testAbortEvent,

  // fetch + signaling
  testAbortedFetch,
  testFetchAndAbort,
  testWorkerAbortedFetch,
  testWorkerFetchAndAbort,
];

function next() {
  if (!steps.length) {
    parent.postMessage({ type: "finish" }, "*");
    return;
  }

  var step = steps.shift();
  step();
}

next();

</script>
